//
//  WheelImageViewController.m
//  FNer
//
//  Created by 王展 on 15/10/8.
//  Copyright (c) 2015年 wangzhan. All rights reserved.
//

#import "WheelImageViewController.h"
#import "AFNetworking.h"
#import "Activity.h"
#import "UIImageView+WebCache.h"
#import "BaseCollectionView.h"
#import "ActivityDetailViewController.h"
#import "WheelCollectionViewCell.h"
#import "DetailHtworld.h"
#import "UserActivityDetailViewController.h"
#import "CommunityDetailTableViewCell.h"
#import "MJRefresh.h"
#import "UserDetaiViewController.h"
#import "UIActivityIndicatorView+AFNetworking.h"


@interface WheelImageViewController ()

@property(nonatomic,retain)UIWebView *webView;
@property(nonatomic,retain)Activity *aActivity;
@property(nonatomic,retain)BaseCollectionView *huodongCV;
@property(nonatomic,retain)UIImageView *bigimageView;
@property(nonatomic,retain)UIView *bigView;
@property(nonatomic,retain)UITapGestureRecognizer *ctap;
@property(nonatomic,retain)UILabel *titleLabel;
@property(nonatomic,retain)UILabel *contentLabel;
@property(nonatomic,retain)NSMutableArray *htWorldArray;
@property(nonatomic,retain)UITableView *communityDetailTV;
@property(nonatomic,retain)NSMutableArray *pindaoArray;
@property(nonatomic,retain)UILabel *atitleLabel;

@property(nonatomic,retain)UIActivityIndicatorView *activity;

@end

@implementation WheelImageViewController

//视图将要显示触发
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //删除self.view上的所有子视图
    for(UIView *view in [self.view subviews])
    {
        [view removeFromSuperview];
    }
    
    //为self.view上添加指定视图
    if (self.alunbo.bulletinType == 1) {
        
        self.atitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        self.atitleLabel.text = @"专题";
        self.atitleLabel.textAlignment = NSTextAlignmentCenter;
        self.atitleLabel.font = [UIFont systemFontOfSize:18 * XWIDTH];
        self.atitleLabel.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = self.atitleLabel;
        
        NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
        if ([string isEqualToString:@"yes"]) {
#warning 改的颜色
            self.atitleLabel.textColor = [UIColor blackColor];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
    
        [self setZhuantiView];
    }
    else if (self.alunbo.bulletinType == 4){
        
        self.atitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        self.atitleLabel.text = @"活动";
        self.atitleLabel.textAlignment = NSTextAlignmentCenter;
        self.atitleLabel.font = [UIFont systemFontOfSize:18 * XWIDTH];
        self.atitleLabel.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = self.atitleLabel;
        
        NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
        if ([string isEqualToString:@"yes"]) {
#warning 改的颜色
            self.atitleLabel.textColor = [UIColor blackColor];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
        
        [self setHuodongView];
        
        [self addHuodongHeaderRefresh];
        
    }
    else if (self.alunbo.bulletinType == 2){
        
        self.atitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        self.atitleLabel.text = @"频道";
        self.atitleLabel.textAlignment = NSTextAlignmentCenter;
        self.atitleLabel.font = [UIFont systemFontOfSize:18 * XWIDTH];
        self.atitleLabel.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = self.atitleLabel;
        
        NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
        if ([string isEqualToString:@"yes"]) {
#warning 改的颜色
            self.atitleLabel.textColor = [UIColor blackColor];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
        
        [self setPindaoView];
        
        [self addPindaoHeaderRefresh];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //初始化的地方
    
    self.bigView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 290 * XHIGHT)];
    self.bigimageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 180 * XHIGHT)];
    self.ctap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigImageAction)];
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 185 * XHIGHT, 250 * XWIDTH, 20 * XHIGHT)];
    self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 205 * XHIGHT, WIDTH - 20 * XWIDTH, 80 * XHIGHT)];
    
    //左方返回按钮
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
}

//加频道下拉刷新
-(void)addPindaoHeaderRefresh
{
 
   
    
    self.communityDetailTV.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
          [self getPindaoData];
        
        
    }];
    
     [self.communityDetailTV.header  beginRefreshing];

    
}



//加活动下拉刷新
-(void)addHuodongHeaderRefresh
{
   
    
    self.huodongCV.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getUserActivityData];
        [self getHuodongWheelDetailData];

        
    }];
    
      [self.huodongCV.header  beginRefreshing];
    
    
    
}

//点击左方返回按钮触发事件
-(void)leftButtonAction
{
    [self.navigationController popViewControllerAnimated:NO];
}

//获取轮播图详情数据
-(void)getHuodongWheelDetailData
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.imzhitu.com/ztworld/label_queryLabelByName"];
    
    AFNetworkReachabilityManager *Netmanger = [AFNetworkReachabilityManager sharedManager];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    //有body体的
    NSDictionary *body = @{@"labelName":self.alunbo.link};
#warning 轮播图详情COOKIE
    //有Cookie的
    NSString *cookieStr = [NSString stringWithFormat:@"    IMZHITU_REMEMBER_ME_COOKIE=QjFuK0Nmc1RleEl4VTVvSW02a0R4UT09OkJreEI0c1BuYkI4YWRKV3JocitTd0E9PQ; JSESSIONID=444A1130F5376C095EF2207F505A7B0B; SERVERID=f2bba00007611e8b21e74f5166ce6604|1444696245|1444696238"];

    [manager.requestSerializer setValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager POST:url_string parameters:body  success:^(NSURLSessionDataTask *operation, id responseObject) {
        [Netmanger stopMonitoring];
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *activityDic = [bigDic objectForKey:@"activity"];
        self.aActivity = [[Activity alloc] init];
        [self.aActivity setValuesForKeysWithDictionary:activityDic];
        
        [self.huodongCV reloadData];

        
    }failure:^(NSURLSessionDataTask *operation, NSError *error) {
   
        
    }];
    
    
    
    
}

//获得活动轮播图用户详情数据
-(void)getUserActivityData
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.imzhitu.com/ztworld/label_queryLabelWorldV2"];
    AFNetworkReachabilityManager *Netmanger = [AFNetworkReachabilityManager sharedManager];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //有body体的
    NSLog(@"labelName : %@",self.alunbo.link);
    NSDictionary *body = @{@"labelName":self.alunbo.link,@"maxId":@"0",@"start":@"1",@"limit":@"20",@"trimExtras":@"false",@"commentLimit":@"2",@"likedLimit":@"10",@"trimValid":@"true"};

#warning 轮播图COOKIE
//    //有Cookie的
    NSString *cookieStr = [NSString stringWithFormat:@"IMZHITU_REMEMBER_ME_COOKIE=QjFuK0Nmc1RleEl4VTVvSW02a0R4UT09OkJreEI0c1BuYkI4YWRKV3JocitTd0E9PQ; JSESSIONID=444A1130F5376C095EF2207F505A7B0B; SERVERID=f2bba00007611e8b21e74f5166ce6604|1444696245|1444696238"];
    
    [manager.requestSerializer setValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    
    [manager POST:url_string parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        self.htWorldArray = [NSMutableArray array];
        NSMutableDictionary *bigDic = responseObject;
        NSMutableArray *bigArray = [bigDic objectForKey:@"htworld"];
        for (NSMutableDictionary *dic in bigArray) {
            DetailHtworld *ahtWorld = [[DetailHtworld alloc] init];
            [ahtWorld setValuesForKeysWithDictionary:dic];
            
            ahtWorld.aUser = [[BaseModel alloc] init];
            [ahtWorld.aUser setValuesForKeysWithDictionary:ahtWorld.userInfo];
            
            [self.htWorldArray addObject:ahtWorld];
        }
        
        [self.huodongCV.header endRefreshing];
        [self.huodongCV reloadData];

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        [self.huodongCV.header endRefreshing];

        
    }];
    
}

//创建活动类型的轮播图详情视图
-(void)setHuodongView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH, 500 * XHIGHT);
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, 330 * XHIGHT);
    
    self.huodongCV = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) collectionViewLayout:flowLayout];
    self.huodongCV.delegate = self;
    self.huodongCV.dataSource = self;
    [self.huodongCV registerClass:[WheelCollectionViewCell class] forCellWithReuseIdentifier:@"acreuse"];
    [self.huodongCV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
              withReuseIdentifier:@"headView"];
    [self.view addSubview:self.huodongCV];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.htWorldArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WheelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"acreuse" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.ahtWorld = [self.htWorldArray objectAtIndex:indexPath.row];
    
    return cell;
}

//创建活动类轮播图头视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headView" forIndexPath:indexPath];
    
    self.bigView.backgroundColor = [UIColor whiteColor];
    [reusableView addSubview:self.bigView];

    [self.bigimageView sd_setImageWithURL:[NSURL URLWithString:self.aActivity.titlePath]];
    [self.bigView addSubview:self.bigimageView];
    
    self.bigimageView.userInteractionEnabled = YES;
    [self.bigimageView addGestureRecognizer:self.ctap];
    
    self.titleLabel.textColor = [UIColor grayColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15 * XHIGHT];
    self.titleLabel.text = self.aActivity.activityName;
    [self.bigView addSubview:self.titleLabel];
    
    self.contentLabel.textColor = [UIColor lightGrayColor];
    self.contentLabel.font = [UIFont systemFontOfSize:12 * XHIGHT];
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.text = self.aActivity.activityDesc;
    [self.bigView addSubview:self.contentLabel];
    
    return reusableView;
}

//轻拍活动类轮播图触发事件
-(void)bigImageAction
{
    if (![self.aActivity.activityLink  isEqual: @""]) {
        ActivityDetailViewController *activityDetailVC = [[ActivityDetailViewController alloc] init];
        [self.navigationController pushViewController:activityDetailVC animated:NO];
        activityDetailVC.aActivity = self.aActivity;
    }
}


//创建专题类型的轮播图详情视图
-(void)setZhuantiView
{
    //创建WebView
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64)];
    self.webView.backgroundColor = [UIColor blackColor];
    self.webView.delegate = self;
    [self.webView setScalesPageToFit:YES];
    NSString *wangZhi = self.alunbo.link;
    NSLog(@"1111%@",wangZhi);
    NSURL *url = [NSURL URLWithString:wangZhi];
    NSURLRequest *requset = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:requset];
    [self.view addSubview:self.webView];
    
    //创建小菊花
    _activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activity.center =self.view.center;
    [self.view addSubview:_activity];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UserActivityDetailViewController *userActivityDetailVC = [[UserActivityDetailViewController alloc] init];
    [self.navigationController pushViewController:userActivityDetailVC animated:NO];
    
    userActivityDetailVC.ahtWorld = [self.htWorldArray objectAtIndex:indexPath.row];
}

//创建频道轮播图详情
-(void)setPindaoView
{
    self.communityDetailTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375 * XWIDTH, 667 * XHIGHT - 64) style:UITableViewStylePlain];
    self.communityDetailTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.communityDetailTV.backgroundColor = [UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1];
    [self.view addSubview:self.communityDetailTV];
    self.communityDetailTV.delegate = self;
    self.communityDetailTV.dataSource = self;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.pindaoArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    CommunityDetailTableViewCell *detailCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (detailCell == nil) {
        detailCell = [[CommunityDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    detailCell.contentView.backgroundColor = [UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1];
    
    detailCell.aDetailHT = [self.pindaoArray objectAtIndex:indexPath.row];
    
    return detailCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0 * XHIGHT;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 500 * XHIGHT;
}

-(void)getPindaoData
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.imzhitu.com/operations/channel_queryChannelWorld"];
    
    NSString *string = [NSString stringWithFormat:@"%@",self.alunbo.link];
    NSDictionary *body = @{@"channelId":string,@"maxId":@"0",@"start":@"1",@"limit":@"10",@"trimExtras":@"false",@"commentLimit":@"2",@"likedLimit":@"10",@"completeLimit":@"10"};
    
    AFNetworkReachabilityManager *Netmanger = [AFNetworkReachabilityManager sharedManager];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    
    [manager GET:url_string parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        self.pindaoArray = [NSMutableArray array];
        NSMutableDictionary *bigDic = responseObject;
        NSMutableArray *bigArray = [bigDic objectForKey:@"htworld"];
        for (NSMutableDictionary *dic in bigArray) {
            DetailHtworld *aDetailHT = [[DetailHtworld alloc] init];
            [aDetailHT setValuesForKeysWithDictionary:dic];
            aDetailHT.aUser = [[BaseModel alloc] init];
            [aDetailHT.aUser setValuesForKeysWithDictionary:aDetailHT.userInfo];
            [self.pindaoArray addObject:aDetailHT];
        }
        
        [self.communityDetailTV.header endRefreshing];
        [self.communityDetailTV reloadData];

        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [self.communityDetailTV.header endRefreshing];
        NSLog(@"没有网络");

        
        
    }];
  }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserDetaiViewController *userDetailVC = [[UserDetaiViewController alloc] init];
    [self.navigationController pushViewController:userDetailVC animated:NO];
    
    userDetailVC.DetailHT = [self.pindaoArray objectAtIndex:indexPath.row];
}

-(void)changeColoring:(NSNotification *)notification
{
#warning 改的颜色
    self.atitleLabel.textColor = [UIColor blackColor];
    
    NSString *string = [notification object];
    if ([string isEqualToString:@"no"]) {
        
#warning 原有颜色
        self.atitleLabel.textColor = [UIColor whiteColor];
    }
    //保存当前状态值
    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"nighting"];
}






-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [_activity startAnimating];
    
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_activity stopAnimating];
    
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [_activity stopAnimating];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
